package jmine.tec.hydra.send.impl.script;

import jmine.tec.hydra.HydraMessages;
import jmine.tec.hydra.api.HydraMessage;
import jmine.tec.hydra.domain.senderRegistry.ScriptSenderRegistry;
import jmine.tec.hydra.exception.HydraException;
import jmine.tec.hydra.script.DispatchScriptContext;
import jmine.tec.hydra.send.Sender;
import jmine.tec.script.ScriptExecutorException;

/**
 * Sender do Hydra que delega para um script o dispatch da mensagem.
 * 
 * @author jrenaut
 */
public class ScriptSender implements Sender {

    private ScriptSenderRegistry registry;

    /**
     * @param ssr {@link ScriptSenderRegistry}
     */
    public ScriptSender(ScriptSenderRegistry ssr) {
        this.registry = ssr;
    }

    /**
     * {@inheritDoc}
     */
    public void send(HydraMessage message) {
        try {
            this.registry.getDispatchScript().createContext(DispatchScriptContext.class).prepare(message).dispatchExecution();
        } catch (ScriptExecutorException e) {
            String mneSystem = message.getSystem() != null ? message.getSystem().getMnemonico() : "null";
            throw new HydraException(HydraMessages.SEND_UNEXPECTED_ERROR.create(message.getId(), mneSystem), e);
        }
    }
}
